<template>
  <div>
    <customDialog
      :title="`${title}`"
      :dialogVisible="dialogVisible"
      @close="closeDialog(ruleFormRef)"
      @confirm="confirmDialog(ruleFormRef)"
      width="800"
      v-loading="loading"
    >
      <div>
        <el-form
          ref="ruleFormRef"
          :model="formData"
          :rules="rules"
          label-position="right"
          label-width="140px"
          class="form_box"
        >
          <el-row>
            <el-col :span="20">
              <el-form-item label="小程序主键Id" prop="id">
                <el-input
                  v-model.number="formData.id"
                  placeholder="小程序主键Id"
                  clearable
                  :disabled="title !== '新增小程序'"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="20">
              <el-form-item label="小程序AppId" prop="appId">
                <el-input
                  v-model="formData.appId"
                  placeholder="请输入小程序ID"
                  clearable
                  :disabled="title !== '新增小程序'"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="20">
              <el-form-item label="小程序名称" prop="appName">
                <el-input
                  v-model="formData.appName"
                  placeholder="请输入小程序名称"
                  clearable
                  maxlength="20"
                  show-word-limit
                  :disabled="title !== '新增小程序'"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="20">
              <el-form-item label="小程序首页路径" prop="pathIndex">
                <el-input
                  v-model="formData.pathIndex"
                  placeholder="请输入小程序首页路径"
                  clearable
                  maxlength="50"
                  show-word-limit
                  autocomplete="off"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="20">
              <el-form-item label="小程序秘钥" prop="secret">
                <el-input
                  v-model="formData.secret"
                  placeholder="请输入小程序秘钥"
                  clearable
                  type="password"
                  show-password
                  autocomplete="off"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="20">
              <el-form-item label="公司主体">
                <el-input
                  v-model.number="formData.company"
                  placeholder="公司主体"
                  clearable
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="title == '新增小程序'">
            <el-col :span="20">
              <el-form-item label="小程序类型" prop="appType">
                <el-select
                  v-model="formData.appType"
                  placeholder="请选择"
                  @change="changeApp"
                >
                  <el-option label="微信" value="wx" />
                  <el-option label="抖音" value="dy" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 微信 -->
          <template v-if="formData.appType === 'wx'">
            <el-row>
              <el-col :span="20">
                <el-form-item label="小程序原始id" prop="appGhId">
                  <el-input
                    v-model="formData.appGhId"
                    placeholder="请输入小程序原始id"
                    clearable
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="20">
                <el-form-item label="虚拟支付Appkey" prop="appKey">
                  <el-input
                    v-model="formData.appKey"
                    placeholder="请输入小程序虚拟支付Appkey"
                    clearable
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="20">
                <el-form-item label="虚拟支付应用Id" prop="offerId">
                  <el-input
                    v-model="formData.offerId"
                    placeholder="请输入小程序虚拟支付应用Id"
                    clearable
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="20">
                <el-form-item label="小程序回调Token" prop="callbackToken">
                  <el-input
                    v-model="formData.callbackToken"
                    placeholder="请输入小程序回调Token"
                    clearable
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="20">
                <el-form-item label="回调AesKey" prop="callbackKey">
                  <el-input
                    v-model="formData.callbackKey"
                    placeholder="请输入小程序回调EncodingAesKey"
                    clearable
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </template>
          <!-- 抖音 -->
          <template v-if="formData.appType === 'dy'">
            <el-row>
              <el-col :span="20">
                <el-form-item label="抖音公钥" prop="dyPublicKey">
                  <el-input
                    v-model="formData.dyPublicKey"
                    placeholder="请输入抖音公钥"
                    clearable
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="20">
                <el-form-item label="抖音应用公钥" prop="dyAppPublicKey">
                  <el-input
                    v-model="formData.dyAppPublicKey"
                    placeholder="请输入抖音应用公钥"
                    clearable
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </template>
          <el-row>
            <el-col :span="20">
              <el-form-item label="是否主体小程序" prop="isWxMain">
                <el-switch
                  v-model="formData.isWxMain"
                  style="

--el-switch-on-color: #13ce66"
                  inline-prompt
                  active-text="是"
                  inactive-text="否"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="!formData.isWxMain">
            <el-col :span="20">
              <el-form-item label="主体小程序" prop="wxMainAppId">
                <el-select v-model="formData.wxMainAppId" placeholder="请选择">
                  <el-option
                    v-for="item in WXOptions"
                    :key="item?.id"
                    :label="item?.label"
                    :value="item?.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </customDialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive } from "vue";
import customDialog from "@/components/CustomDialog/index.vue";
import {
  addWxApp,
  updateWxApp,
  addDyApp,
  updateDyApp,
  getAppDetail,
  getAppOptions,
} from "@/api/operateCenter/apps/index";
import type { FormInstance } from "element-plus";
import { ElMessage } from "element-plus";
import { cloneDeep } from "lodash-es";

const ruleFormRef = ref<FormInstance>();
const dialogVisible = ref(false);
const loading = ref(false);
const form = {
  id: undefined,
  appId: "",
  appName: "", // 小程序名称
  secret: "", // 小程序秘钥
  pathIndex: "", // 小程序路径_首页
  company: "", // 公司主体

  appGhId: "", // 小程序原始 Id
  appKey: "", // 小程序虚拟支付 App Key
  offerId: "", // 小程序虚拟支付应用 Id
  callbackToken: "", // 小程序回调 Token
  callbackKey: "", // 小程序回调 EncodingAesKey
  isWxMain: true, // 是否微信主体小程序

  dyPublicKey: "", // 抖音公钥  -- dy
  dyAppPublicKey: "", // 抖音应用公钥  -- dy
  appType: "wx",
  wxMainAppId: "", // 微信主体小程序
};
const formData = ref(Object.assign({}, form));
const title = ref<string>("");
const WXOptions = ref<Array<any>>([]);

// 正整数
const intRules = (rule: any, value: any, callback: any) => {
  // 匹配包含4-15位的整数正则表达式
  let reg = /^[1-9]\d{3,14}$/;
  if (!value) {
    callback(new Error("请输入小程序主键Id"));
  } else if (!reg.test(value)) {
    callback(new Error("请输入4~15位之间的整数"));
  } else {
    callback();
  }
};
// 小程序AppId rulus
const mixAppId = (rule: any, value: any, callback: any) => {
  let reg = /^[a-zA-Z0-9_/@]{8,25}$/;
  let tips = "位之间的字符（数字/字母/下划线/@）";
  if (!value) {
    callback(new Error("请输入小程序密钥"));
  } else if (value && !reg.test(value)) {
    callback(new Error(`请输入8~25${tips}`));
  } else {
    callback();
  }
};
// 小程序秘钥Secret rulus
const rulesSecret = (rule: any, value: any, callback: any) => {
  let ret = /^[a-zA-Z0-9_/@]{10,45}$/;
  console.log("rule----", rule, value, title.value);
  let tips = "位之间的字符（数字/字母/下划线/@）";
  if (title.value == "新增小程序") {
    if (!value) {
      callback(new Error("请输入小程序密钥"));
    } else if (!ret.test(value)) {
      callback(new Error(`请输入10~45${tips}`));
    } else {
      callback();
    }
  } else {
    if (value && !ret.test(value)) {
      callback(new Error(`请输入10~45${tips}`));
    } else {
      callback();
    }
  }
};
// 微信必须
const mustRules = (rule: any, value: any, callback: any) => {
  let reg = /^[a-zA-Z0-9_/@]{8,25}$/;
  let ret = /^[a-zA-Z0-9_/@]{10,45}$/;
  let tips = "位之间的字符（数字/字母/下划线/@）";
  if (!value) {
    if (rule?.field == "appGhId") {
      callback(new Error("请输入小程序原始ID"));
    } else if (rule?.field == "appKey") {
      callback(new Error("请输入小程序虚拟支付密钥"));
    }
  } else if (value && !reg.test(value) && rule?.field == "appGhId") {
    callback(new Error(`请输入8~25${tips}`));
  } else if (value && !ret.test(value) && rule?.field == "appKey") {
    callback(new Error(`请输入10~45${tips}`));
  } else {
    callback();
  }
};
// 微信rules
const wxRules = (rule: any, value: any, callback: any) => {
  console.log("rule----", rule, value);
  // 匹配包含数字、字母或者下划线的10-20位正则表达式
  let reg = /^[a-zA-Z0-9_/@]{8,25}$/;
  let ret = /^[a-zA-Z0-9_/@]{10,45}$/;
  let tips = "位之间的字符（数字/字母/下划线/@）";
  if (value && !reg.test(value) && rule?.field == "offerId") {
    callback(new Error(`请输入8~25${tips}`));
  } else if (
    value &&
    !ret.test(value) &&
    (rule?.field == "callbackToken" || rule?.field == "callbackKey")
  ) {
    callback(new Error(`请输入10~45${tips}`));
  } else {
    callback();
  }
};
// // 抖音公钥 rules
// const dyRules = (rule: any, value: any, callback: any) => {
//   let ret = /^[a-zA-Z0-9_/@]{10,45}$/;
//   let tips = "位之间的字符（数字/字母/下划线/@）";
//   if (value && !ret.test(value)) {
//     callback(new Error(`请输入10~45${tips}`));
//   } else {
//     callback();
//   }
// };

// message: "请输入小程序名称",
const rules = reactive({
  id: [{ required: true, validator: intRules, trigger: "blur" }],
  appId: [{ required: true, validator: mixAppId, trigger: "blur" }],
  appName: [{ required: true, message: "请输入小程序名称", trigger: "blur" }],
  pathIndex: [
    { required: true, message: "请输入小程序首页路径", trigger: "blur" },
  ],
  secret: [{ required: true, validator: rulesSecret, trigger: "blur" }],

  appGhId: [{ required: true, validator: mustRules, trigger: "blur" }],
  appKey: [{ required: true, validator: mustRules, trigger: "blur" }],
  offerId: [{ required: false, validator: wxRules, trigger: "blur" }],
  callbackToken: [{ required: false, validator: wxRules, trigger: "blur" }],
  callbackKey: [{ required: false, validator: wxRules, trigger: "blur" }],

  // dyPublicKey: [{ required: false, validator: dyRules, trigger: "blur" }],
  // dyAppPublicKey: [{ required: false, validator: dyRules, trigger: "blur" }],
  appType: [{ required: true, message: "请选择小程序类型", trigger: "change" }],
  wxMainAppId: [
    { required: true, message: "请选择主体小程序", trigger: "change" },
  ],
});

watch(
  () => title.value,
  (val: string) => {
    if (val == "新增小程序") {
      console.log("rules.value---", rules);
      rules.secret[0].required = true;
    } else {
      rules.secret[0].required = false;
    }
  }
);

// 切换小程序类型
const changeApp = (type: string) => {
  if (type === "wx") {
    formData.value.appGhId = "";
    formData.value.appKey = "";
    formData.value.offerId = "";
    formData.value.callbackToken = "";
    formData.value.callbackKey = "";
  } else if (type === "dy") {
    formData.value.dyPublicKey = "";
    formData.value.dyAppPublicKey = "";
  }
  getMainApp(type);
  formData.value.isWxMain = true;
  formData.value.wxMainAppId = "";
};

// 关闭
const closeDialog = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl?.resetFields();
  Object.assign(formData.value, form);
  dialogVisible.value = false;
};

// 成功
const emit = defineEmits(["success"]);
const confirmDialog = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      let URL;
      if (title.value === "新增小程序") {
        URL = formData.value.appType == "wx" ? addWxApp : addDyApp;
      } else {
        URL = formData.value.appType == "wx" ? updateWxApp : updateDyApp;
      }
      formData.value.id = formData.value.id || undefined;
      loading.value = true;
      URL(formData.value).then((res: Record<string, any>) => {
        ElMessage.success(
          `${title.value != "新增小程序" ? "编辑" : "新增"}成功`
        );
        dialogVisible.value = false;
        emit("success");
        closeDialog(ruleFormRef.value);
        loading.value = false;
      });
    }
  });
};

// 父级电子显示dialog
const showDialog = (val: any) => {
  // console.log("显示弹窗----", val?.appType, val);
  dialogVisible.value = true;
  title.value = val ? `编辑小程序-${val?.appName}` : "新增小程序";
  let type = val ? val?.appType : "wx";
  getMainApp(type);
  if (val) {
    getAppDetails(val?.id);
  }
};

// 获取小程序详情
const getAppDetails = (val: number) => {
  getAppDetail(val).then((res) => {
    formData.value = cloneDeep(res);
    // formData.value.isWxMain = !formData.value.isWxMain ? false : true;
    formData.value.wxMainAppId = !formData.value.isWxMain
      ? formData.value.wxMainAppId
      : "";
    // console.log("详情数据----", formData.value);
  });
};

// 获取微信小程序下拉选项
const getMainApp = (type = "wx") => {
  let params = {
    appType: type,
    isWxMain: true,
  };
  getAppOptions(params).then((res: Record<string, any>) => {
    WXOptions.value = res?.map((item: Record<string, any>) => {
      return {
        label: item.appName,
        id: item.appId.toString(),
      };
    });
  });
};

defineExpose({
  showDialog,
});
</script>

<style scoped lang="scss">
.form_box {
  padding: 0 20px;
}
</style>
